package com.malu.mimicqqbot.handlers;




import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import kotlin.text.UStringsKt;
import love.forte.simbot.component.qguild.event.QGAtMessageCreateEvent;
import love.forte.simbot.definition.Member;
import love.forte.simbot.event.ChatGroupMessageEvent;
import love.forte.simbot.message.Messages;
import love.forte.simbot.message.MessagesBuilder;
import love.forte.simbot.quantcat.common.annotations.ContentTrim;
import love.forte.simbot.quantcat.common.annotations.Filter;
import love.forte.simbot.quantcat.common.annotations.Listener;
import org.springframework.boot.http.client.ClientHttpRequestFactoryBuilder;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.util.concurrent.CompletableFuture;

@Component
public class MyHandles {
    private final ClientHttpRequestFactoryBuilder clientHttpRequestFactoryBuilder;

    public MyHandles(ClientHttpRequestFactoryBuilder clientHttpRequestFactoryBuilder) {
        this.clientHttpRequestFactoryBuilder = clientHttpRequestFactoryBuilder;
    }

    /**
     * 此处是一个标准库中通用的类型：聊天群消息事件
     * 在QQ机器人组件中，它的真实实现类型会是QGGroupAtMessageCreateEvent
     */
//    @Listener
//    public CompletableFuture<?> onGroupMessage(ChatGroupMessageEvent event) {
//        System.out.println("ChatGroupMessageEvent: " + event);
//        Member author = event.getAuthor();
//
//
//        System.out.println("author: " + author.getName());
//        System.out.println("author: " + author.getId());
//        System.out.println("author: " + author.getAvatar());
//        System.out.println("author: " + author.getNick());
//        System.out.println("author: " + author.getCoroutineContext());
//        return event.replyAsync("暂时不支持");
//    }
    @Listener
    @ContentTrim
    @Filter("语法 .*")
    public CompletableFuture<?> searchGrammar(ChatGroupMessageEvent event) throws IOException {
        System.out.println("ChatGroupMessageEvent: " + event);
        ClientHttpRequestFactory build = clientHttpRequestFactoryBuilder.build();
        String wordParam = event.getMessageContent().getPlainText().trim().split(" ")[1];
        String responseBodyString = getUrlResponse("http://127.0.0.1:8081/api/jp/grammar/pattern?pattern=" + wordParam);
        System.out.println("responseBodyString: " + responseBodyString);
        StringBuilder r = new StringBuilder();
        try {
            // 使用 Gson 解析 JSON 数组字符串
            Gson gson = new Gson();
            JsonArray jsonArray = gson.fromJson(responseBodyString, JsonArray.class);
            if (jsonArray != null && jsonArray.size() > 0) {
                // 获取数组中的第一个元素
                JsonObject jsonObject = jsonArray.get(0).getAsJsonObject();
                String pattern = jsonObject.get("pattern").getAsString();
                String meaning = jsonObject.get("meaning").getAsString();
                String level = jsonObject.get("level").getAsString();
                r.append("查询结果：\n")
                        .append("语法：").append(pattern).append("\n")
                        .append("解释：").append(meaning).append("\n")
                        .append("等级：").append(level).append("\n\n");


            } else {
                return event.replyAsync("未找到查询结果");
            }
        } catch (Exception e) {
            System.err.println("Failed to parse JSON: " + e.getMessage());
            e.printStackTrace();
            return event.replyAsync("解析查询结果时出现错误");
        }

        return event.replyAsync( r.toString());
    }

    @Listener
    @ContentTrim
    @Filter("查询 .*")
    public CompletableFuture<?> searchWord(ChatGroupMessageEvent event) throws IOException {
        System.out.println("ChatGroupMessageEvent: " + event);
        String wordParam = event.getMessageContent().getPlainText().trim().split(" ")[1];
        String responseBodyString = getUrlResponse("http://127.0.0.1:8081/api/jp/search?word=" + wordParam);


        try {
            // 使用 Gson 解析 JSON 数组字符串
            Gson gson = new Gson();
            JsonArray jsonArray = gson.fromJson(responseBodyString, JsonArray.class);
            if (jsonArray != null && jsonArray.size() > 0) {
                // 获取数组中的第一个元素
                JsonObject jsonObject = jsonArray.get(0).getAsJsonObject();
                System.out.println("Parsed JSON Object: " + jsonObject);
                // 你可以根据需求从 jsonObject 中获取具体的值
                String word = jsonObject.get("japanese_word").getAsString();
                String kana = jsonObject.get("kana").getAsString();
                String chineseExplanation = jsonObject.get("chinese_explanation").getAsString();
                String level = jsonObject.get("level").getAsString();

                String resultStr = "查询结果：\n" +
                        "单词：" + word + "\n" +
                        "假名：" + kana + "\n" +
                        "中文解释：" + chineseExplanation + "\n" +
                        "等级：" + level;
                return event.replyAsync(resultStr);
            } else {
                return event.replyAsync("未找到查询结果");
            }
        } catch (Exception e) {
            System.err.println("Failed to parse JSON: " + e.getMessage());
            e.printStackTrace();
            return event.replyAsync("解析查询结果时出现错误");
        }
    }

    public String getUrlResponse(String url) throws IOException {
        ClientHttpRequestFactory build = clientHttpRequestFactoryBuilder.build();
        ClientHttpRequest request = build.createRequest(URI.create(url), HttpMethod.GET);
        ClientHttpResponse execute = request.execute();
        java.io.InputStream bodyStream = execute.getBody();
        java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(bodyStream));
        StringBuilder responseBody = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            responseBody.append(line);
        }
        return responseBody.toString();
    }
    /**
     * 此处监听的是QQ机器人组件中的专属类型：QQ频道中文字子频道的At消息。
     * 并且过滤消息：消息中的文本消息去除前后空字符后，等于 '你好'
     */
    @Listener
    @ContentTrim
    @Filter("你好")
    public CompletableFuture<?> onMessage(QGAtMessageCreateEvent event) {
        System.out.println("QGAtMessageCreateEvent: " + event);

        return event.replyAsync("你也好");
        // 可以直接返回任意 Future 类型，
        // 或者返回 EventResult，其中包裹着 Future 类型。
    }
}